/**
 * 
 */
package com.huxi.lang.local.support;

import static com.huxi.lang.local.DateUtils.DEFAULT_TO_DAY_FORMAT;
import static com.huxi.lang.local.DateUtils.DEFAULT_TO_TIMESTAMP_FORMAT;
import static com.huxi.lang.local.DateUtils.toZoneOffset;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.time.ZoneOffset;
import java.util.Calendar;
import java.util.Objects;
import java.util.TimeZone;

import com.huxi.lang.local.DateContext;

/**
 * @author jian.wu
 * @since 1.0
 */
public class AbstractDateContext implements DateContext {

	private final TimeZone timeZone;
	private final ZoneOffset zoneOffset;
	private final boolean lenient;

	protected AbstractDateContext(TimeZone timeZone, ZoneOffset zoneOffset, boolean lenient) {
		this.timeZone = Objects.requireNonNull(timeZone, "TimeZone must be not null");
		this.zoneOffset = Objects.requireNonNull(zoneOffset, "ZoneOffset must be not null");
		this.lenient = lenient;
	}

	protected AbstractDateContext(TimeZone timeZone) {
		this(timeZone, toZoneOffset(timeZone), false);
	}

	@Override
	public TimeZone getTimeZone() {
		return timeZone;
	}

	@Override
	public ZoneOffset getZoneOffset() {
		return zoneOffset;
	}

	/**
	 * 新建本地日历
	 * 
	 * @return 本地日历，非空。
	 * @since 1.0
	 */
	protected Calendar createCalendar() {
		Calendar calendar = Calendar.getInstance(timeZone);
		calendar.setLenient(lenient);
		return calendar;
	}

	@Override
	public Format createDateFormat(String pattern) {
		SimpleDateFormat fmt = new SimpleDateFormat(pattern);
		fmt.setTimeZone(timeZone);
		fmt.setLenient(lenient);
		return fmt;
	}

	@Override
	public Format getDateFormat() {
		return createDateFormat(DEFAULT_TO_DAY_FORMAT);
	}

	@Override
	public Format getTimestampFormat() {
		return createDateFormat(DEFAULT_TO_TIMESTAMP_FORMAT);
	}

	@Override
	public Calendar getCalendar() {
		return createCalendar();
	}

}
